package com.yuntongxun.ecdemo.rest;

import android.content.Context;
import android.content.Intent;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.ui.account.LoginActivity;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import retrofit.Callback;
import retrofit.ErrorHandler;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.converter.GsonConverter;

/**
 * Created by EVE on 2016/4/17.
 */
public final class RetrofitUtil {

    private static final String API_URL = "http://121.40.20.102/imserver";

    private static class gsonUTCdateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {

        private final DateFormat dateFormat;

        public gsonUTCdateAdapter() {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());      //This is the format I need
            dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));                               //This is the key line which converts the date to UTC which cannot be accessed with the default serializer
        }

        @Override
        public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
            return new JsonPrimitive(dateFormat.format(date));
        }

        @Override
        public synchronized Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) {
            try {
                return dateFormat.parse(jsonElement.getAsString());
            } catch (java.text.ParseException e) {
                throw new JsonParseException(e);
            }
        }
    }

    private static Gson _gson = new GsonBuilder()
            .registerTypeAdapter(Date.class, new gsonUTCdateAdapter())
            .create();

    public static <T> T createRestApi(Class<T> type) {

        T restApi = new RestAdapter.Builder()
                .setServer(API_URL)
                .setRequestInterceptor(CookieManager.getInstance())
                .setConverter(new GsonConverter(_gson))
                .setErrorHandler(new CustomExceptionHandler()) // not work ?
                .build()
                .create(type);

        return restApi;
    }

    public static class CustomExceptionHandler implements ErrorHandler {
        @Override
        public Throwable handleError(RetrofitError cause) {
            Response response = cause.getResponse();
            LogUtil.w("mylog.retrofit", String.format("%d,%s", response.getStatus(), response.getReason()));
            if(response.getStatus() == 401) {
                try {
                    Context context = CCPAppManager.getContext();
                    if(context != null) {
                        context.startActivity(new Intent(context, LoginActivity.class));
                        return new Exception(context.getString(R.string.please_login));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return cause;
        }
    }
}
